// 权限控制，如果用户没有登录，则跳转到登录页面
import router from '@/router'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { asyncRoutes } from '@/router'

// 根据权限标识过滤路由表
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}
// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}
// 设置白名单
const whiteList = ['/login', '/404']
// 全局路由守卫
router.beforeEach(async(to, from, next) => {
  const token = getToken()
  if (token) {
    next()
    if (!store.state.user.profile.id) {
      // 获取原始权限列表
      const permissions = await store.dispatch('user/getProfile')
      // 把后端的权限数组格式变成我们自己的两个权限数据
      console.log('当前的权限数据位：', permissions)
      console.log('动态路由', asyncRoutes)
      // 1.一级路由菜单标识
      const firstRoutePerms = getFirstRoutePerms(permissions)
      console.log('一级路由权限', firstRoutePerms)
      let filterRoutes = []
      if (firstRoutePerms.includes('*')) {
        filterRoutes.push(...asyncRoutes)
      } else {
        // 2.二级路由菜单标识
        const secondRoutePerms = getSecondRoutePerms(permissions)
        console.log('二级路由权限', secondRoutePerms)
        filterRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
      }
      // 4.addRoute动态添加
      filterRoutes.forEach(route => router.addRoute(route))
      console.log('动态路由', filterRoutes)
      // 5.存入vuex渲染左侧菜单
      store.commit('menu/setMenuList', filterRoutes)
      next(to.path)
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
